const PENDING = 'penging'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'

function MyPromise(fn) {
  const that = this // 代码可能会异步执行，用于获取正确的 this 对象
  that.state = PENDING
  // value 变量用于保存 resolve 或者 reject 中传入的值
  // resolvedCallbacks 和 rejectedCallbacks 用于保存 then 中的回调，因为当执行完 Promise 时状态可能还是等待中，这时候应该把 then 中的回调保存起来用于状态改变时使用
  that.value = null
  that.resolvedCallbacks = []
  that.rejectedCallbacks = []

  // 待完善 resolve 和 reject 函数

  // 待完善执行 fn 函数


  // 如何执行 Promise 中传入的函数
  try {
    fn(resolve, reject)
  } catch (e) {
    reject(e)
  }

}



// 首先两个函数都得判断当前状态是否为等待中，因为规范规定只有等待态才可以改变状态
// 将当前状态更改为对应状态，并且将传入的值赋值给 value
// 遍历回调数组并执行
function resolve(value) {
  if (that.state === PENDING) {
    that.state = RESOLVED
    that.value = value
    that.resolvedCallbacks.map(cb => cb(that.value))
  }
}

function reject(value) {
  if (that.state === PENDING) {
    that.state = REJECTED
    that.value = value
    that.rejectedCallbacks.map(cb => cb(that.value))
  }
}




// 最后我们来实现较为复杂的 then 函数
MyPromise.prototype.then = function (onFulfilled, onRejected) {
  const that = this
  onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
  onRejected =
    typeof onRejected === 'function'
      ? onRejected
      : r => {
        throw r
      }
  if (that.state === PENDING) {
    that.resolvedCallbacks.push(onFulfilled)
    that.rejectedCallbacks.push(onRejected)
  }
  if (that.state === RESOLVED) {
    onFulfilled(that.value)
  }
  if (that.state === REJECTED) {
    onRejected(that.value)
  }
}